package unrn.isiii.bean;

import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import unrn.isiii.dao.CtaCorrienteDao;
import unrn.isiii.dao.TaskDao;
import unrn.isiii.model.CtaCorriente;
import unrn.isiii.model.Task;

@Component("ctaCorrienteController")
public class CtaCorrienteController {

	private static final Logger logger = LoggerFactory
			.getLogger(CtaCorrienteController.class);

	private CtaCorriente ctaCorriente = new CtaCorriente();
	private List<CtaCorriente> ctasCorrientes;

	@Autowired
	private CtaCorrienteDao ctaCorrienteDao;

	public String getMessage() {
		logger.debug("Returning message from task home bean");
		return "Hello from Spring";
	}

	public CtaCorriente getCtaCorriente() {
		return ctaCorriente;
	}

	public CtaCorrienteDao getCtaCorrienteDao() {
		return ctaCorrienteDao;
	}

	public void setCtaCorrienteDao(CtaCorrienteDao ctaCorrienteDao) {
		this.ctaCorrienteDao = ctaCorrienteDao;
	}

	public void setCtaCorriente(CtaCorriente ctaCorriente) {
		this.ctaCorriente = ctaCorriente;
	}

	public void setctasCorrientes(List<CtaCorriente> ctasCorrientes) {
		this.ctasCorrientes = ctasCorrientes;
	}

	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public void savectaCorriente() {
		if (ctaCorriente.getId() == null)
			ctaCorrienteDao.create(ctaCorriente);
		else
			ctaCorrienteDao.update(ctaCorriente);
		ctaCorriente = new CtaCorriente();
		FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Alta",
				"realizada con exito.");
		if (FacesContext.getCurrentInstance() != null)
			FacesContext.getCurrentInstance().addMessage(null, msg);
		invalidateTasks();
	}

	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public void eliminar(Long id) {
		ctaCorrienteDao.delete(id);
		FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Alta",
				"realizada con exito.");
		if (FacesContext.getCurrentInstance() != null)
			FacesContext.getCurrentInstance().addMessage(null, msg);
		invalidateTasks();
	}

	private void invalidateTasks() {
		ctasCorrientes = null;
	}

	public List<CtaCorriente> getctasCorrientes() {
		if (ctasCorrientes == null) {
			ctasCorrientes = ctaCorrienteDao.findAll();
		}
		return ctasCorrientes;
	}

	public void seleccionarctaCorriente(CtaCorriente ctaCorriente) {
		setCtaCorriente(ctaCorriente);
	}
}
